package com.jokesoft.feedback.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jokesoft.feedback.core.service.FeedBackDto;
import com.jokesoft.feedback.core.service.FeedBackService;

public class FeedBackerServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    ApplicationContext applicationContext = null;

    private FeedBackService service;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (applicationContext == null) {
            System.out.println("setting context in post");
            applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        }
        if (applicationContext != null && applicationContext.containsBean("feedBackServiceImpl")) {
            service = (FeedBackService) applicationContext.getBean("feedBackServiceImpl");
        }

        String name = "";
        String email = "";
        String feedback = "";

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Palaute</title></head>");
        out.println("<body>Kiitos palautteestasi!!!!<br><br></body>");
        out.println("<body>");

        @SuppressWarnings("unchecked")
        Enumeration<String> e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String nimi = e.nextElement();
            String[] arvot = request.getParameterValues(nimi);
            for (int i = 0; i < arvot.length; i++) {
                out.println(nimi + ": " + arvot[i] + "<br>");
                // Calling service
                // First get all needed values
                // TODO: Change DTO to builder one
                if (nimi.equals("nimi"))
                    name = arvot[i];
                if (nimi.equals("sposti"))
                    email = arvot[i];
                if (nimi.equals("palaute"))
                    feedback = arvot[i];

            }
            out.println("</body></html>");
        }

        FeedBackDto feedbackDto = new FeedBackDto(name, email, feedback);

        service.addFeedBack(feedbackDto);

    }
}
